<template>
  <!-- 诊断录入弹窗：左侧表格操作区 + 右侧信息区 -->
  <el-dialog v-model="visibleProxy" title="下诊断" width="87vw" :close-on-click-modal="false">
    <div class="dialog-content">
      <!-- 左侧：表格与操作 -->
      <div class="left-pane">
        <div class="left-pane-heard">
          <div class="patient-info">
            <div class="patient-diagnose">本次住院 {{ patient.admissionDiagnosis }}</div>
            <div class="patient-name">{{ patient.patientName }} {{ patient.admissionDiagnosis }}</div>
          </div>
          <div class="toolbar">
            <el-button class="add-btn op-btn" type="primary" @click="handleSave">完成</el-button>
            <el-button class="info-btn op-btn" @click="handleCopy">复制</el-button>
            <el-button class="del-btn op-btn" type="danger" :disabled="!selection.length" @click="handleDelete"
              >删除</el-button
            >
          </div>
        </div>

        <el-table
          :data="rows"
          border
          size="small"
          @selection-change="onSelectionChange"
          :row-key="rowKey"
          class="diagnosis-table"
        >
          <el-table-column type="selection" width="48" align="center" />
          <el-table-column label="诊断类型" prop="type" width="120" align="center">
            <template #default="{ row }">
              <el-select v-model="row.diagnosesType" placeholder="请选择">
                <el-option
                  v-for="dict in sys_diagnoses_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="diseaseType" width="90" align="center" />
          <el-table-column label="诊断" prop="diagnosesContent" max-width="260" align="center">
            <template #default="{ row }">
              <el-select
                v-model="diagnoses"
                filterable
                remote
                reserve-keyword
                placeholder="请输入诊断"
                :remote-method="remoteDiagnosesMethod"
                :loading="diagnosesLoading"
                @change="val => handleDiagnosesChange(row, val)"
                style="width: 100%"
              >
                <el-option
                  v-for="item in diagnosesOptions"
                  :key="item.diseaseId"
                  :label="item.diseaseName"
                  :value="item.diseaseId"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="主诊断" prop="mainDiagnoses" width="80" align="center">
            <template #default="{ row }">
              <el-select v-model="row.mainDiagnoses">
                <el-option label="是" value="1" />
                <el-option label="否" value="2" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="diagnosesStatus" width="90" align="center">
            <template #default="{ row }">
              <el-select v-model="row.diagnosesStatus">
                <el-option
                  v-for="dict in sys_diagnoses_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="ICD" prop="icd" width="120" align="center" />
          <el-table-column label="发病日期" prop="onsetDate" width="132" align="center">
            <template #default="{ row }">
              <el-date-picker
                :prefix-icon="null"
                v-model="row.onsetDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="诊断日期" prop="diagnosisDate" width="132" align="center">
            <template #default="{ row }">
              <el-date-picker
                :prefix-icon="null"
                v-model="row.diagnosisDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
                style="width: 100%"
              />
            </template>
          </el-table-column>
          <el-table-column label="诊断医生" prop="doctorName" width="80" align="center">
            <template #default="{ row }">
              <span class="cell-text">{{ row.doctorName || userName }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 右侧：患者信息与历史诊断 -->
      <div class="right-pane">
        <div class="history-list">
          <div class="history-title">历史诊断</div>
          <div v-if="!historyList || !historyList.length" class="history-empty">暂无数据</div>
          <ul v-else>
            <li v-for="(h, idx) in historyList" :key="idx">
              <span class="history-type">{{ h.diagnosesType }}</span>
              <span class="history-name">{{ h.diagnosesContent }}</span>
              <span class="history-meta">{{ h.doctorName }} · {{ h.diagnosisDate }}</span>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed } from 'vue'
import { addDiagnoses, getDiseaseList } from '@/api/residentDoctor/clinicalRecords'
import useUserStore from '@/store/modules/user'

const proxy = getCurrentInstance().proxy

const { sys_diagnoses_type, sys_diagnoses_status } = proxy.useDict('sys_diagnoses_type', 'sys_diagnoses_status')

const props = defineProps({
  visible: { type: Boolean, default: false },
  patient: { type: Object, default: () => ({}) },
  historyList: { type: Array, default: () => [] }
})
const userName = computed(() => useUserStore()?.nickName || useUserStore()?.name)
const userId = computed(() => useUserStore()?.userId)
const emit = defineEmits(['update:visible', 'save'])

const visibleProxy = computed({
  get: () => props.visible,
  set: v => emit('update:visible', v)
})
// 表格数据与选中
const selection = ref([])
const newDiagnosisList = ref([
  {
    diagnosesType: '',
    diseaseType: '',
    diagnosesContent: '',
    mainDiagnoses: '否',
    diagnosesStatus: '确诊',
    icd: '',
    onsetDate: '',
    diagnosisDate: today(),
    doctorName: userName.value,
    diagnosingDoctorId: userId.value
  }
])
const rows = computed(() => [...props.historyList, ...newDiagnosisList.value])

function today() {
  const d = new Date()
  const y = d.getFullYear()
  const m = String(d.getMonth() + 1).padStart(2, '0')
  const dd = String(d.getDate()).padStart(2, '0')
  return `${y}-${m}-${dd}`
}

// 疾病目录查询
const diagnosesLoading = ref(false)
const diagnosesOptions = ref([])
const diagnoses = ref({})

function remoteDiagnosesMethod(query) {
  diagnosesLoading.value = true
  getDiseaseList({
    pageNum: 1,
    pageSize: 100,
    searchKey: query
  }).then(res => {
    diagnosesLoading.value = false
    if (res.code === 200) {
      diagnosesOptions.value = res.data || []
    } else {
      console.error(res)
    }
  })
}

function handleDiagnosesChange(row, val) {
  const item = diagnosesOptions.value.find(i => i.diseaseId === val)
  console.log(item)

  row.diagnosesContent = item.diseaseName
  row.diseaseType = item.diseaseType
  row.icd = item.diseaseCoding
}

function createEmptyRow() {
  return [...props.historyList, ...newDiagnosisList.value]
}

function rowKey(row, index) {
  return index
}

function onSelectionChange(sel) {
  selection.value = sel
}

function handleCopy() {
  if (selection.value.length) {
    const copy = { ...selection.value[0] }
    newDiagnosisList.value = { ...copy }
  } else {
    rows.value = [createEmptyRow()]
  }
}

function handleDelete() {
  if (!selection.value.length) {
    proxy.$modal.notifyWarning('请先选择要删除的行')
    return
  }
  const set = new Set(selection.value)
  newDiagnosisList.value = newDiagnosisList.value.filter(r => !set.has(r))
  selection.value = []
  if (!rows.value.length) rows.value = [createEmptyRow()]
}

function validateRow(row) {
  if (!row.diagnosesType || !row.diseaseType || !row.diagnosesContent || !row.icd || !row.diagnosisDate) return false
  if (
    row.onsetDate &&
    new Date(row.diagnosisDate.replace(/-/g, '/')).getTime() < new Date(row.onsetDate.replace(/-/g, '/')).getTime()
  )
    return false
  return true
}

function handleSave() {
  const invalid = newDiagnosisList.value.filter(r => !validateRow(r))
  if (invalid.length) {
    proxy.$modal.notifyError('请完善必填项并确保日期合法')
    return
  }
  const data = newDiagnosisList.value.map(r => ({
    ...r,
    patientId: props.patient.patientId,
    hospitalizationNumber: props.patient.hospitalizationNumber
  }))
  addDiagnoses(data).then(res => {
    if (res.code === 200) {
      emit(
        'save',
        newDiagnosisList.value.map(r => ({ ...r }))
      )
      proxy.$modal.notifySuccess('保存成功')
    } else {
      console.error(res)
    }
  })
}
</script>

<style scoped lang="scss">
@use '@/assets/styles/variables.module.scss' as *;

.dialog-content {
  display: flex;
  flex-wrap: wrap;
  gap: $margin-md;
}

.left-pane {
  background: #fff;
  border-radius: $border-radius;
  padding: $padding-sm;
  flex: 1;
  width: 60vw;
  &-heard {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: $margin-sm;
  }
  .patient-info {
    display: flex;
    align-items: center;
    gap: $margin-sm;
    .patient-diagnose {
      font-weight: 600;
      max-width: 300px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .patient-name {
      color: $sub-font-color;
    }
  }
}

.toolbar {
  display: flex;
  gap: $margin-sm;
  justify-content: flex-start;
  margin-bottom: $margin-sm;
}

.right-pane {
  max-width: 36vw;
  min-width: 20vw;
  background: #fff;
  border-radius: $border-radius;
  padding: $padding-sm;
}

.patient-card {
  margin-bottom: $margin-md;
  .patient-line {
    margin-bottom: 4px;
  }
  .strong {
    font-weight: 600;
  }
  .muted {
    color: $sub-font-color;
    margin-left: $margin-sm;
  }
}

.history-title {
  font-weight: 600;
  margin-bottom: $margin-sm;
}
.history-empty {
  color: $sub-font-color;
}
.history-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}
.history-list li {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px solid $border-color;
}
.history-type {
  color: $sub-font-color;
  margin-right: $margin-sm;
}
.history-name {
  flex: 1;
}
.history-meta {
  color: $sub-font-color;
}

.cell-text {
  color: #303133;
}
.diagnosis-table {
  :deep(.el-select__wrapper) {
    box-shadow: none;
  }
  :deep(.el-input__wrapper) {
    box-shadow: none;
  }
}
</style>
